package com.example.listenmailforfsbot.util;

import okhttp3.*;
import org.apache.commons.lang.StringUtils;

import java.io.IOException;
import java.util.Objects;

/**
 * @author dftdla
 */
public class SendFeiShuBot {

    private String HOST;
    private String regexStr;

    @Override
    public String toString() {
        return "SendFeiShuBot{" + "\n" +
                "\t\tHOST.length = " + HOST.length() + "\n" +
                "\t\tregexStr = '" + regexStr + '\'' + "\n" +
                "\t}";
    }

    public SendFeiShuBot(String webHookUrl, String regexStr) {
        this.HOST = webHookUrl;
        this.regexStr = regexStr;
    }

    public Integer getHostLen(){
        return HOST.length();
    }

    public Boolean checkHost(String url){
        return HOST.equals(url);
    }

    public String sendMessageToBot(String text){

        System.out.println("接收到发送任务：" + text);
        text = text.replaceAll("[\\\\]", " ");
        text = text.replaceAll("[\b\r\n\t\"]", " ");
        text = text.replaceAll(regexStr,"");
        System.out.println("处理后的文本：" + text);

        if(StringUtils.isBlank(text)){
            System.out.println("处理后文本为空,终止发送到WebHook");
            return null;
        }

        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();

        MediaType mediaType = MediaType.parse("application/json");

        String json =
                "{\n" +
                        "    \"msg_type\": \"text\",\n" +
                        "    \"content\":{\n" +
                        "        \"text\":\"" + text +"\"\n" +
                        "    }\n" +
                        "}";

        RequestBody body = RequestBody.create(mediaType, json);

        Request request = new Request.Builder()
                .url(HOST)
                .post(body)
                .build();

        try {
            System.out.println("已发送请求:" + json);
            Response response = client.newCall(request).execute();
            return Objects.requireNonNull(response.body()).string().contains("success") ?"success": Objects.requireNonNull(response.body()).string();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

    }

}
